var fs = require('fs');
var url = require('url');
var http = require('http');
var https = require('https');
var querystring = require('querystring');

var Vtil = function(opts){

    var inner = {};

    inner.opts = {
        debug: true,
        logFile: __dirname + '/../runtime/app.log'
    };

    inner.get = function(reqUrl, data, cb) {
        var argLen = arguments.length;
        if (argLen > 0) {
            var opts = reqUrl;
            var qstr = '';
            ('object' == typeof(data)) && (qstr = '?' + querystring.stringify(data));
            ('string' == typeof(reqUrl)) && (opts = url.parse(reqUrl + qstr));
            ('function' == typeof(data)) && (cb = data);
            var mod = ('http:' == opts.protocol) ? http : https;
            mod.get(opts, function(res){
                var trunks = [];
                res.on('data', function(trunk){
                    trunks.push(trunk);
                }).on('end', function(){
                    var data = new Buffer.concat(trunks);
                    cb(null, data);
                });
            }).on('error', function(err){
                cb(err);
            });
        } else {
            throw new Error('Too less arguments');
        }
    };

    inner.log = function(data) {
        var output = (arguments.length > 1) ? arguments : data;
        inner.opts.debug && console.log(output);
        if (inner.opts.debug && inner.opts.logFile) {
            var str = output;
            (str != 'string') && (str = JSON.stringify(output));
            var line = new Date().toString() + ': ' + str + '\n';
            fs.appendFile(inner.opts.logFile, line, function(err){
                if (err) throw err;
            });
        }
    };

    return {
        get: inner.get,
        log: inner.log
    };

};

exports = module.exports = Vtil;
